package com.example.demo.module.filter;

import com.example.demo.util.JwtTokenUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;

public class JWTAuthorizationFilter extends BasicAuthenticationFilter {
    public JWTAuthorizationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String tokenHeader=request.getHeader(JwtTokenUtils.TOKEN_HEADER);
        //如果请求头里面没有Authorization信息那么直接放行
        if(tokenHeader==null||!tokenHeader.startsWith(JwtTokenUtils.TOKEN_PREFIX)){
            chain.doFilter(request,response);
            return;
        }
        //如果请求头里面有token，则进行解析，并且设置认证信息
        SecurityContextHolder.getContext().setAuthentication(getAuthentication(tokenHeader));
        super.doFilterInternal(request,response,chain);
        Object principal=SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        System.out.println("header"+SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
        System.out.println("header"+SecurityContextHolder.getContext().getAuthentication().getAuthorities().toString());

        //super.doFilterInternal(request, response, chain);
    }
    //在这里从token里面获取用户信息并且新建一个token
    private UsernamePasswordAuthenticationToken getAuthentication(String tokenHeader){
        String token =tokenHeader.replace(JwtTokenUtils.TOKEN_PREFIX,"");
        String username=JwtTokenUtils.getUsername(token);
        String role=JwtTokenUtils.getUserRole(token);
        if(username!=null){
            return new UsernamePasswordAuthenticationToken(username,null,Collections.singleton(new SimpleGrantedAuthority(role)));

        }
        return null;
    }
}
